<template>
    <view>
        <video v-show="showVideo"
         style="width: 100%;" id="video" 
         :style="{height:full?'calc(100vh - 10px)':''}"
         ref="video"
         preload="auto"
         autoplay
         @play="handlePlayVideo"
         @pause="handlePauseVideo"
         @ended="handleEndVideo"
         @progress="handleLoaded($event,0)"
         fill controls>
         </video>
        
        <h-audio ref="audio" :backImage="audioBackImage" @status="handleChangeStatus" @loadedmetadata="handleLoaded" v-show="showAudio" :playbackRate="backRate" :audio="audioUrl"></h-audio>   
      
        <view class="control-btns" v-if="!full">
            <button v-if="!hideSwitch" type="default" plain class="mini-btn" @click="changeMediaType" size="mini">切换{{mediaType === 0?'音频':'视频'}}</button>
            <picker :value="2"  mode="selector" @change="handleConfirmBackRate" range-key="name" :range="backRateList">
                    <button type="default"  plain size="mini">倍数{{backRateText}}</button>
            </picker>
			
        </view>
        
    </view>
</template>

<script>
    import { clearKeys } from "../../api/book.js";
    import Hls from "../../static/hls.js"
    import HAudio from '../h-custom-audio/index.vue'
    export default {
        name:"a-video",
        components:{HAudio},
        props:{
            videoUrl:{
                type:String,
                default:''
            },
            audioUrl:{
                type:String,
                default:''
            },
            audioOnly:{
                type:Boolean,
                default:false,
            },
            videoOnly:{
                type:Boolean,
                default:false,
                
            },
            audioBackImage:{
                type:String,
                default:''
            },
            hideSwitch:{
                type:Boolean,
                default:false
            },
            full:{
                type:Boolean,
                default:false,
            },
        },
        computed:{
            showAudio(){return this.videoOnly || this.audioOnly?this.audioOnly:this.mediaType === 1},
            showVideo(){return this.videoOnly || this.audioOnly?this.videoOnly:this.mediaType === 0}
        },
        watch:{
          videoPlaying:{
              handler(val){
                  this.handleChangeStatus(val)
              }
          }  
        },
        data() {
            return {
                mediaType:0,
                backRate:1,
                videoPlaying:false,
                backRateText:"1.0x",
                videoLoaded:false,
                audioLoaded:false,
                isClear:false,
                alreadPlay:false,
                backRateList:[
                    { name:"0.5x", value:0.5},
                    { name:"0.75x", value:0.75},
                    { name:"1.0x", value:1},
                    { name:"1.25x", value:1.25},
                    { name:"1.5x", value:1.5},
                    { name:"1.75x", value:1.75},
                    { name:"2.0x", value:2}
                    
                ],
                
            };
        },
        methods:{
            init(){
                var video = document.querySelector("#video .uni-video-video");
                var hasReady=false
                if (Hls.isSupported() && /m3u8/.test( this.videoUrl)) {
                    hasReady=true
                  var hls = new Hls();
                  hls.loadSource(this.videoUrl);
                  hls.attachMedia(video);
                  hls.on(Hls.Events.MANIFEST_PARSED, function() {
                      video.play();
                  })
                }
                if(!hasReady){
                    video.src=this.videoUrl
                    video.addEventListener('loadedmetadata',e=>{
                        uni.hideLoading()
                    })
                    video.addEventListener('canplay',e=>{
                        video.play();
                    })
                    video.addEventListener('loadstart',(e)=>{
                        uni.showLoading({
                            title: '视频加载中',
                            mask:true
                        })                    
                    })
                }
                window.addEventListener('beforeunload',(e)=>{
                    this.handleClearKeys()
                })
                window.addEventListener('pagehide',()=>{
                    this.handleClearKeys()
                })
            },
            isSupported(){
                return document.createElement('video').canPlayType('application/vnd.apple.mpegURL') !== ''
            },
            changeMediaType(){
                if(this.mediaType === 0){
                    if(this.videoPlaying){
                        this.$refs.video.pause()
                    }
                    this.$refs.audio.audioPlay()
                }else{
                    if(this.$refs.audio.isPlay){
                        this.$refs.audio.audioPause()
                    }
                    this.$refs.video.play()
                }
                this.mediaType = this.mediaType === 0?1:0
            },
            handlePlayVideo(){
                this.alreadPlay=true
                this.videoPlaying=true
            },
            handlePauseVideo(){
                this.videoPlaying = false
            },
            handleEndVideo(){
                this.videoPlaying = false
            },
            handleLoaded(e,type){
                if(e.detail.buffered === 100){
                    if(type === 0){
                        this.videoLoaded=true
                    }
                    if(type === 1){
                        this.audioLoaded = true
                    }    
                }
                if(this.videoLoaded && this.audioLoaded){
                    this.handleClearKeys()
                }
            },
            handleChangeStatus(val){
                this.$emit('status',val)
            },
            handleClearKeys(){
                if(this.isClear) return
                this.isClear=true
                clearKeys({keys:[this.audioUrl.split('media/')[1],this.videoUrl.split('media/')[1]]})
            },
            handleConfirmBackRate(v){
                const br = this.backRateList[v.detail.value]
                if(br.value !== this.backRate){
                    this.backRate = br.value
                    this.backRateText = br.name
                    this.$refs.video.playbackRate(br.value)
                }
            }
        },
    }
</script>

<style scoped lang="scss">
.control-btns{
    text-align: right;
    padding-right: 10px;
    margin: 7px 0;
    uni-button{
        margin-right: 10px;
        border-color: #ccc;
    }
    uni-picker{
        display: inline-block;
        uni-button{
            width: 100px;
        }
    }
}

</style>